<template>
    <div class="vehicle-repair-order-page">
        <!-- 顶部搜索区域 -->
        <div class="search-section">
            <el-card shadow="never" class="search-card">
                <div class="search-form">
                    <el-row :gutter="20">
                        <el-col :span="6">
                            <el-input v-model="searchForm.ordernum" placeholder="请输入订单号" clearable :prefix-icon="Search"
                                @clear="handleSearch" @keyup.enter="handleSearch" />
                        </el-col>
                        <el-col :span="6">
                            <el-input v-model="searchForm.name" placeholder="请输入用户昵称" clearable @clear="handleSearch"
                                @keyup.enter="handleSearch" />
                        </el-col>
                        <el-col :span="6">
                            <el-select v-model="searchForm.orderStatus" placeholder="请选择订单状态" clearable
                                @clear="handleSearch" @change="handleSearch">
                                <el-option label="全部" value="" />
                                <el-option label="已完成" value="已完成" />
                                <el-option label="未完成" value="未完成" />
                                <el-option label="已取消" value="已取消" />
                            </el-select>
                        </el-col>
                        <el-col :span="6">
                            <el-button type="primary" :icon="Search" @click="handleSearch">
                                搜索
                            </el-button>
                            <el-button :icon="RefreshRight" @click="handleReset">重置</el-button>
                        </el-col>
                    </el-row>
                </div>
            </el-card>
        </div>

        <!-- 表格区域 -->
        <div class="table-section">
            <el-card shadow="never">
                <!-- 表格头部工具栏 -->
                <div class="table-header">
                    <div class="table-title">
                        <h3>车辆维修订单</h3>
                        <span class="total-count">共 {{ pagination.total }} 条记录</span>
                    </div>
                    <div class="table-actions">
                        <el-button :icon="Refresh" @click="refreshData" :loading="loading">
                            刷新
                        </el-button>
                    </div>
                </div>

                <!-- 数据表格 -->
                <el-table :data="currentPageData" style="width: 100%" v-loading="loading" element-loading-text="加载中..."
                    stripe border>
                    <el-table-column  prop="id" label="序号" width="60" align="center" />
                    <el-table-column prop="order_sn" label="订单号" width="180" show-overflow-tooltip />
                    <el-table-column prop="nickname" label="用户昵称" width="120" show-overflow-tooltip />
                    <el-table-column prop="name" label="消费项目" width="120" />
                    <el-table-column prop="price" label="订单金额" width="120" align="right">
                        <template #default="scope">
                            <span class="amount">¥{{ scope.row.price }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="discount" label="优惠金额" width="120" align="right">
                        <template #default="scope">
                            <span class="discount">¥{{ scope.row.discount }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="deduction" label="加送币抵扣" width="120" align="right">
                        <template #default="scope">
                            <span class="coin">{{ scope.row.deduction }} 币</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="pay_price" label="支付金额" width="120" align="right">

                        <template #default="scope">
                            <span class="payment">¥{{ scope.row.pay_price }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="status" label="订单状态" width="100" align="center">
                        <template #default="scope">
                            <el-tag :type="scope.row.status==1?'warning':'success'" size="small">
                                {{ scope.row.status==1?'未完成':'已完成' }}

                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="addtime" label="订单时间" width="160" />
                    <el-table-column prop="pay_time" label="完成时间" width="160" />
                    <el-table-column label="操作" width="200" fixed="right" align="center">
                        <template #default="scope">
                            <el-button size="small" type="primary" :icon="View" @click="handleView(scope.row)" link>
                                查看
                            </el-button>
                            <el-button size="small" type="success" :icon="Select"
                                @click="handleFinish(scope.row)" link>
                                完成
                            </el-button>
                            <el-button size="small" type="danger"
                                :icon="CloseBold" @click="handleCancel(scope.row)" link>
                                取消
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 分页组件 -->
                <div class="pagination-section">
                    <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
                        :page-sizes="[10, 20, 30, 40]" :total="pagination.total"
                        layout="total, sizes, prev, pager, next, jumper" background @size-change="handleSizeChange"
                        @current-change="handleCurrentChange" />
                </div>
            </el-card>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Select, CloseBold, View, RefreshRight, Refresh } from '@element-plus/icons-vue'
import instance from '../../utils/request'
import { useRouter } from 'vue-router'
const router = useRouter()
const allTableData = ref([])
//获取订单列表
const getProductOrder = async () => {
  let res = await instance.get('Seller/orderList')
  console.log(res);
  
  if(res.msg == '下单成功'){
    allTableData.value = res.data
  }
}

// 响应式数据
const loading = ref(false)

// 搜索表单
const searchForm = reactive({
    ordernum: '',
    name: '',
    orderStatus: ''
})

// 分页配置
const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
})



// 过滤后的数据
const filteredData = computed(() => {
    let data = allTableData.value

    // 根据搜索条件过滤
    if (searchForm.ordernum) {
        data = data.filter(item =>
            item.ordernum.toLowerCase().includes(searchForm.ordernum.toLowerCase())
        )
    }

    if (searchForm.name) {
        data = data.filter(item =>
            item.name.toLowerCase().includes(searchForm.name.toLowerCase())
        )
    }

    if (searchForm.orderStatus) {
        data = data.filter(item => item.orderStatus === searchForm.orderStatus)
    }

    return data
})

// 当前页数据
const currentPageData = computed(() => {
    const start = (pagination.currentPage - 1) * pagination.pageSize
    const end = start + pagination.pageSize
    return filteredData.value.slice(start, end)
})

// 更新分页总数
const updatePagination = () => {
    pagination.total = filteredData.value.length
    // 如果当前页超出范围，重置到第一页
    if (pagination.currentPage > Math.ceil(pagination.total / pagination.pageSize)) {
        pagination.currentPage = 1
    }
}

// 搜索处理
const handleSearch = () => {
    pagination.currentPage = 1
    updatePagination()
}

// 重置搜索
const handleReset = () => {
    searchForm.ordernum = ''
    searchForm.name = ''
    searchForm.orderStatus = ''
    pagination.currentPage = 1
    updatePagination()
}

// 刷新数据
const refreshData = async () => {
    loading.value = true
    try {
        // 模拟API调用延迟
        await new Promise(resolve => setTimeout(resolve, 1000))
        // 这里应该调用实际的API来获取最新数据
        ElMessage.success('数据刷新成功')
    } catch (error) {
        ElMessage.error('数据刷新失败')
    } finally {
        loading.value = false
    }
}

// 分页大小改变
const handleSizeChange = (newSize) => {
    pagination.pageSize = newSize
    pagination.currentPage = 1
    updatePagination()
}

// 当前页改变
const handleCurrentChange = (newPage) => {
    pagination.currentPage = newPage
}

// 获取状态类型（用于标签颜色）
const getStatusType = (status) => {
    switch (status) {
        case '已完成':
            return 'success'
        case '未完成':
            return 'warning'
        case '已取消':
            return 'danger'
        default:
            return 'info'
    }
}

// 查看订单详情
const handleView = (row) => {
    ElMessage.info(`查看订单`)
    // 这里可以添加查看订单详情的逻辑，比如弹出模态框或跳转到详情页
    console.log('查看订单详情：', row)
    router.push(`PrintOrder?id=${row.id}`)



}

// 完成订单
const handleFinish = async (row) => {
    try {
        await ElMessageBox.confirm(
            `确定要将订单标记为已完成吗？`,
            '确认操作',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )

        loading.value = true
        // 模拟API调用
        const res =  await instance.post('Seller/status', {
            id:row.id,
             sta: 2
        })
        if(res.msg == '操作成功'){
            ElMessage.success('订单已完成')
            getProductOrder()
        }
        
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('操作失败，请重试')
        }
    } finally {
        loading.value = false
    }
}

// 取消订单
const handleCancel = async (row) => {
    try {
        await ElMessageBox.confirm(
            `确定要取消订单 ${row.ordernum} 吗？此操作不可撤销！`,
            '确认取消',
            {
                confirmButtonText: '确定取消',
                cancelButtonText: '我再想想',
                type: 'error',
            }
        )

        loading.value = true
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 500))

        // 更新订单状态
        row.orderStatus = '已取消'

        ElMessage.success('订单已取消')
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('操作失败，请重试')
        }
    } finally {
        loading.value = false
    }
}

// 组件挂载时初始化数据
onMounted(() => {
    getProductOrder()
    updatePagination()
})
</script>

<style lang="scss" scoped>
.vehicle-repair-order-page {
    padding: 20px;
    background-color: #f5f7fa;
    min-height: 100vh;

    .search-section {
        margin-bottom: 20px;

        .search-card {
            border: none;
            box-shadow: 0 2px 12px 0 rgba(241, 239, 239, 0.06);

            .search-form {
                padding: 10px 0;

                .el-row {
                    align-items: center;
                }

                .el-button {
                    margin-right: 8px;

                    &:last-child {
                        margin-right: 0;
                    }
                }
            }
        }
    }

    .table-section {
        .el-card {
            border: none;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);

            .table-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 20px;
                padding: 0 0 20px 0;
                border-bottom: 1px solid #ebeef5;

                .table-title {
                    display: flex;
                    align-items: center;
                    gap: 16px;

                    h3 {
                        margin: 0;
                        font-size: 18px;
                        font-weight: 600;
                        color: #303133;
                    }

                    .total-count {
                        // color: #909399;
                        font-size: 14px;
                        background-color: #f4f4f5;
                        padding: 4px 12px;
                        border-radius: 16px;
                    }
                }

                .table-actions {
                    .el-button {
                        margin-left: 8px;
                    }
                }
            }

            // 表格样式优化
            :deep(.el-table) {
                border-radius: 8px;
                overflow: hidden;

                .el-table__header {
                    th {
                        background-color: #fafafa;
                        color: #606266;
                        font-weight: 600;
                        border-bottom: 1px solid #ebeef5;
                    }
                }

                .el-table__body {
                    tr {
                        &:hover {
                            background-color: #f5f7fa;
                        }
                    }

                    td {
                        border-bottom: 1px solid #f0f0f0;
                        padding: 12px 0;
                    }
                }

                // 金额相关样式
                .amount {
                    color: #e6a23c;
                    font-weight: 600;
                }

                .discount {
                    color: #f56c6c;
                    font-weight: 600;
                }

                .coin {
                    color: #409eff;
                    font-weight: 600;
                }

                .payment {
                    color: #67c23a;
                    font-weight: 600;
                    font-size: 14px;
                }

                // 操作按钮样式
                .el-button {
                    margin: 0 4px;
                    padding: 4px 8px;

                    &.el-button--small {
                        font-size: 12px;
                    }
                }
            }

            .pagination-section {
                margin-top: 20px;
                padding-top: 20px;
                border-top: 1px solid #ebeef5;
                display: flex;
                justify-content: center;

                :deep(.el-pagination) {
                    .el-pagination__total {
                        color: #909399;
                    }

                    .el-pager {
                        li {
                            &.is-active {
                                background-color: #409eff;
                                color: white;
                                border-radius: 4px;
                            }

                            &:hover:not(.is-active) {
                                background-color: #f5f7fa;
                                border-radius: 4px;
                            }
                        }
                    }

                    .btn-prev,
                    .btn-next {
                        border-radius: 4px;

                        &:hover {
                            background-color: #f5f7fa;
                        }
                    }
                }
            }
        }
    }
}

// 响应式设计
@media (max-width: 768px) {
    .vehicle-repair-order-page {
        padding: 10px;

        .search-section {
            .search-form {
                .el-col {
                    margin-bottom: 10px;
                }
            }
        }

        .table-section {
            .table-header {
                flex-direction: column;
                gap: 16px;
                align-items: flex-start;

                .table-actions {
                    width: 100%;
                    text-align: right;
                }
            }

            :deep(.el-table) {
                font-size: 12px;

                .el-table__header th,
                .el-table__body td {
                    padding: 8px 4px;
                }
            }

            .pagination-section {
                :deep(.el-pagination) {

                    .el-pagination__sizes,
                    .el-pagination__jump {
                        display: none;
                    }
                }
            }
        }
    }
}

// 暗色主题支持
@media (prefers-color-scheme: dark) {
    .vehicle-repair-order-page {
        // background-color: #1a1a1a;

        // .search-card,
        // .el-card {
        //     background-color: #2d2d2d;
        //     border-color: #404040;
        // }

        .table-title h3 {
            color: #ffffff;
        }

        // .total-count {
        //     background-color: #404040;
        //     color: #cccccc;
        // }
    }
}

// 动画效果
.el-table__row {
    transition: background-color 0.3s ease;
}

.el-button {
    transition: all 0.3s ease;
}

// 状态标签自定义样式
:deep(.el-tag) {
    border-radius: 12px;
    font-weight: 500;

    &.el-tag--success {
        background-color: #f0f9ff;
        border-color: #67c23a;
        color: #67c23a;
    }

    &.el-tag--warning {
        background-color: #fdf6ec;
        border-color: #e6a23c;
        color: #e6a23c;
    }

    &.el-tag--danger {
        background-color: #fef0f0;
        border-color: #f56c6c;
        color: #f56c6c;
    }
}
</style>